#!/bin/bash

run()
{
	# pre_define test_groups
	basic_test_list="check_license check_specfile check_codestyle check_source check_pkg_version"
	rpm_test_list="pkg_smoke_test check_abi_diff check_pkg_dependency whl_pkg_smoke_test"
	custom_test_list="custom_script"

	[ -n "$group" ] || die "No group is specified"
	if [ "$group" == "basic_test" ]; then
		target_tests=$basic_test_list
	elif [ "$group" == "rpm_test" ]; then
		target_tests=$rpm_test_list
	elif [ "$group" == "custom_test" ]; then
		target_tests=$custom_test_list
	else
		echo "${group} is not supported"
		return 1
	fi

	for t in $target_tests; do
		if [ "X$TONE_TESTCASES" == "X" ] || [[ "$TONE_TESTCASES" =~ "$t" ]]; then
			if [ $t == "custom_script" ]; then
				if [ "X$TONE_CUSTOM_SCRIPT" == "X" ]; then
					echo "Custom script not set"
					echo "====SKIP: custom_script"
					continue
				fi

				# fetch package source tree
				repo_url=${PKG_CI_REPO_URL}
				repo_name=$(basename $PKG_CI_REPO_URL .git)
				repo_branch=${PKG_CI_REPO_BRANCH}
				patch_url="${PKG_CI_REPO_URL/\.git/}/pulls/${PKG_CI_PR_ID}.patch"
				patch_name=$(basename $patch_url)
				[ -d "$repo_name" ] && rm -rf $repo_name
				[ -f "$patch_name" ] && rm -rf $patch_name
				logger "git clone -b $repo_branch $repo_url"
				logger "wget $patch_url"
				logger "cd $repo_name"
				git config user.email "test@example.com"
				git config user.name "test"
				logger "git am ../$patch_name"
				logger "export PKG_CI_SRC_PATH=$(pwd)"

				echo "====Run Custom Script: $TONE_CUSTOM_SCRIPT"
				custom_script
				if [ $? -eq 0 ]; then
					echo "====PASS: custom_script"
				else
					echo "====FAIL: custom_script"
				fi
			elif [ $t == "pkg_smoke_test" ]; then
				echo "$TONE_TESTCASES" | grep "whl_pkg_smoke_test" >/dev/null || {
					./run_package_citest.sh -t $t
				}
				continue
			else
				./run_package_citest.sh -t $t
			fi
		else
			echo "$t skip,  $t not include in ($TONE_TESTCASES)"
		fi
	done

}

parse()
{
	$TONE_BM_SUITE_DIR/parse.awk
}
    
